package com.heer.imagepick;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.NonNull;
import android.text.TextUtils;
import android.util.SparseBooleanArray;
import android.view.KeyEvent;
import android.view.View;
import android.widget.GridView;
import android.widget.Toast;

import com.heer.cropimage.Contants;
import com.heer.cropimage.CropActivity;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

import java.io.File;
import java.util.ArrayList;

@SuppressLint("NewApi")
public class PhotoWallMultipleActivity extends Activity {
    private ArrayList<String> list;
    private GridView mPhotoWall;
    private PhotoWallMultipleAdapter adapter;

    /**
     * 当前文件夹路径
     */
    private String currentFolder = null;
    /**
     * 当前展示的是否为最近照片
     */
    private boolean isLatest = true;

    TitleBuilder titleBuilder;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.photo_wall);
        EventBus.getDefault().register(this);

        titleBuilder = new TitleBuilder(this);
        titleBuilder.setTitleText("最近照片").setLeftText("返回相册").setLeftImage(R.drawable.ic_back).setLeftOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                backAction();
            }
        }).setRightText("确定").setRightOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                EventBus.getDefault().post("wall");
                ArrayList<String> paths = getSelectImagePaths();
                Intent intent = new Intent();
                intent.putExtra("code", paths != null ? 100 : 101);
                intent.putStringArrayListExtra("paths", paths);
                setResult(100, intent);
                finish();
            }
        });

        mPhotoWall = (GridView) findViewById(R.id.photo_wall_grid);
        list = Utility.getLatestImagePaths(this, 99);
        list.add(0, "index");
        adapter = new PhotoWallMultipleAdapter(this, list, mHandler);
        mPhotoWall.setAdapter(adapter);
    }

    Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 0:
                    Toast.makeText(PhotoWallMultipleActivity.this, "最多选择9张图片",
                            Toast.LENGTH_SHORT).show();
                    break;

                default:
                    break;
            }
        }
    };
    /**
     * 第一次跳转至相册页面时，传递最新照片信息
     */
    private boolean firstIn = true;

    /**
     * 点击返回时，跳转至相册页面
     */
    private void backAction() {
        Intent intent = new Intent(this, PhotoAlbumlMultipleActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
        // 传递“最近照片”分类信息
        if (firstIn) {
            if (list != null && list.size() > 0) {
                intent.putExtra("latest_count", list.size());
                intent.putExtra("latest_first_img", list.get(1));
            }
            firstIn = false;
        }
        startActivity(intent);
        // 动画
        overridePendingTransition(R.anim.in_from_left, R.anim.out_from_right);
    }

    // 重写返回键
    @Override
    public boolean onKeyDown(int keyCode, @NonNull KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            backAction();
            return true;
        } else {
            return super.onKeyDown(keyCode, event);
        }
    }

    /**
     * 根据图片所属文件夹路径，刷新页面
     */
    @SuppressLint("NewApi")
    private void updateView(int code, String folderPath) {
        list.clear();
        adapter.clearSelectionMap();
        adapter.notifyDataSetChanged();
        adapter.setCount(0);
        if (code == 100) { // 某个相册
            int lastSeparator = folderPath.lastIndexOf(File.separator);
            String folderName = folderPath.substring(lastSeparator + 1);
            titleBuilder.setTitleText(folderName);
            list.addAll(Utility.getAllImagePathsByFolder(folderPath));
        } else if (code == 200) { // 最近照片
            titleBuilder.setTitleText("最近照片");
            ArrayList<String> list_near = Utility.getLatestImagePaths(this, 99);
            list_near.add(0, "index");
            list.addAll(list_near);
        }
        adapter.notifyDataSetChanged();
        if (list.size() > 0) {
            // 滚动至顶部
            mPhotoWall.smoothScrollToPosition(0);
        }
    }


    // 获取已选择的图片路径
    private ArrayList<String> getSelectImagePaths() {
        SparseBooleanArray map = adapter.getSelectionMap();
        if (map.size() == 0) {
            return null;
        }
        ArrayList<String> selectedImageList = new ArrayList<String>();
        for (int i = 0; i < list.size(); i++) {
            if (map.get(i)) {
                selectedImageList.add(list.get(i));
            }
        }
        return selectedImageList;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    @Subscribe
    public void finish(String str) {
        if (TextUtils.equals(str, "album"))
            finish();
    }

    // 从相册页面跳转至此页
    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);

        // 动画
        overridePendingTransition(R.anim.in_from_right, R.anim.out_from_left);

        int code = intent.getIntExtra("code", -1);
        if (code == 100) {
            // 某个相册
            String folderPath = intent.getStringExtra("folderPath");
            if (isLatest
                    || (folderPath != null && !folderPath.equals(currentFolder))) {
                currentFolder = folderPath;
                updateView(100, currentFolder);
                isLatest = false;
            }
        } else if (code == 200) {
            // “最近照片”
            if (!isLatest) {
                updateView(200, null);
                isLatest = true;
            }
        }
    }

    private void startPhotoCrop(Uri uri, String duplicatePath, int reqCode) {
        Intent intent = new Intent(Contants.CROP_ACTIVITY);
        intent.putExtra(CropActivity.IMAGE_URI, uri);
        startActivityForResult(intent, reqCode);
        /**
         * intent.setDataAndType(uri, "image/*"); intent.putExtra("crop",
         * "true"); intent.putExtra("outputFormat", "JPEG"); // aspectX aspectY
         * �ǿ�ߵı��� intent.putExtra("aspectX", 1); intent.putExtra("aspectY",
         * 1); // outputX outputY �ǲü�ͼƬ��� intent.putExtra("outputX", reqCode
         * == REQ_CODE_BG_CROP ? BG_CROP_WIDTH : AVATAR_CROP_WIDTH);
         * intent.putExtra("outputY", reqCode == REQ_CODE_BG_CROP ?
         * BG_CROP_HEIGHT : AVATAR_CROP_HEIGHT);
         * intent.putExtra(MediaStore.EXTRA_OUTPUT, duplicateUri);
         * intent.putExtra("return-data", true);
         */

    }

    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        try {
            if (resultCode == 0) {
                return;
            } else if (requestCode == 1) {// 加载本地图片
            } else if (requestCode == 2) {// 裁剪图片
                File f = new File(adapter.getSD_CARD_TEMP_DIR());
                Uri uri = Uri.fromFile(f);
                startPhotoCrop(uri, null, 3);
            } else if (requestCode == 3) {// 裁剪结果返回
                if (data.getExtras() != null) {
                    // 选择图片完成,回到起始页面
                    ArrayList<String> paths = new ArrayList<String>();
                    String cropPath = adapter.getSD_CARD_TEMP_DIR()
                            .replace(".", "_crop_image.").trim();
                    paths.add(cropPath);
                    Intent intent = new Intent();
                    intent.putExtra("code", paths != null ? 100 : 101);
                    intent.putStringArrayListExtra("paths", paths);
                    setResult(100, intent);
                    finish();
                }
            }
        } catch (Exception e) {
            return;
        }
    }
}